<template>
  <div class="user-management">
    <AdminTable
      title="用户管理"
      :columns="columns"
      :data="users"
      :pagination="pagination"
      @create="handleCreate"
      @edit="handleEdit"
      @delete="handleDelete"
      @search="handleSearch"
      @change-page="handleChangePage"
    />
    
    <!-- 用户编辑/创建模态框 -->
    <div v-if="showModal" class="modal-overlay" @click="closeModal">
      <div class="modal-content" @click.stop>
        <div class="modal-header">
          <h3>{{ isEditing ? '编辑用户' : '创建用户' }}</h3>
          <button class="close-btn" @click="closeModal">×</button>
        </div>
        <div class="modal-body">
          <form @submit.prevent="saveUser">
            <div class="form-group">
              <label>用户名</label>
              <input type="text" v-model="currentUser.user_account" required />
            </div>
            <div class="form-group">
              <label>昵称</label>
              <input type="text" v-model="currentUser.nickname" required />
            </div>
            <div class="form-group">
              <label>邮箱</label>
              <input type="email" v-model="currentUser.email" />
            </div>
            <div class="form-group">
              <label>角色</label>
              <select v-model="currentUser.user_role">
                <option value="user">普通用户</option>
                <option value="admin">管理员</option>
              </select>
            </div>
            <div class="form-group">
              <label>状态</label>
              <select v-model="currentUser.status">
                <option :value="1">启用</option>
                <option :value="0">禁用</option>
              </select>
            </div>
            <div class="form-actions">
              <button type="button" @click="closeModal" class="btn btn-secondary">取消</button>
              <button type="submit" class="btn btn-primary">保存</button>
            </div>
          </form>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, onMounted } from 'vue'
import AdminTable from '../components/AdminTable.vue'
import { userAPI } from '../../../api/index.js'

export default {
  name: 'UserList',
  components: {
    AdminTable
  },
  setup() {
    const users = ref([])
    const pagination = ref({
      page: 1,
      size: 10,
      total: 0
    })
    
    const showModal = ref(false)
    const isEditing = ref(false)
    const currentUser = ref({
      id: null,
      user_account: '',
      nickname: '',
      email: '',
      user_role: 'user',
      status: 1
    })
    
    const columns = [
      { key: 'id', title: 'ID' },
      { key: 'user_account', title: '用户名' },
      { key: 'nickname', title: '昵称' },
      { key: 'email', title: '邮箱' },
      { key: 'user_role', title: '角色' },
      { key: 'create_time', title: '创建时间', type: 'date' },
      { key: 'status', title: '状态', type: 'status' }
    ]
    
    const fetchUsers = async (page = 1, search = '') => {
      try {
        const response = await userAPI.getUsers({
          page: page,
          size: pagination.value.size,
          search: search
        })
        
        users.value = response.data.users
        pagination.value.total = response.data.total
        pagination.value.page = page
      } catch (error) {
        console.error('Failed to fetch users:', error)
      }
    }
    
    const handleCreate = () => {
      isEditing.value = false
      currentUser.value = {
        id: null,
        user_account: '',
        nickname: '',
        email: '',
        user_role: 'user',
        status: 1
      }
      showModal.value = true
    }
    
    const handleEdit = (user) => {
      isEditing.value = true
      currentUser.value = { ...user }
      showModal.value = true
    }
    
    const handleDelete = async (user) => {
      try {
        await userAPI.deleteUser(user.id)
        fetchUsers(pagination.value.page)
      } catch (error) {
        console.error('Failed to delete user:', error)
        alert('删除用户失败')
      }
    }
    
    const handleSearch = (query) => {
      fetchUsers(1, query)
    }
    
    const handleChangePage = (page) => {
      fetchUsers(page)
    }
    
    const saveUser = async () => {
      try {
        if (isEditing.value) {
          await userAPI.updateUser(currentUser.value.id, currentUser.value)
        } else {
          await userAPI.createUser(currentUser.value)
        }
        closeModal()
        fetchUsers(pagination.value.page)
      } catch (error) {
        console.error('Failed to save user:', error)
        alert('保存用户失败')
      }
    }
    
    const closeModal = () => {
      showModal.value = false
    }
    
    onMounted(() => {
      fetchUsers()
    })
    
    return {
      users,
      pagination,
      columns,
      showModal,
      isEditing,
      currentUser,
      handleCreate,
      handleEdit,
      handleDelete,
      handleSearch,
      handleChangePage,
      saveUser,
      closeModal
    }
  }
}
</script>

<style scoped>
.user-management {
  padding: 20px;
}

.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.modal-content {
  background: white;
  border-radius: 8px;
  width: 100%;
  max-width: 500px;
  max-height: 90vh;
  overflow-y: auto;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  border-bottom: 1px solid #eee;
}

.modal-header h3 {
  margin: 0;
  color: #2c3e50;
}

.close-btn {
  background: none;
  border: none;
  font-size: 24px;
  cursor: pointer;
  color: #7f8c8d;
}

.modal-body {
  padding: 20px;
}

.form-group {
  margin-bottom: 20px;
}

.form-group label {
  display: block;
  margin-bottom: 5px;
  color: #2c3e50;
  font-weight: 500;
}

.form-group input,
.form-group select {
  width: 100%;
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 14px;
  box-sizing: border-box;
}

.form-actions {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>